var app = getApp();
var ApiUrl = app.globalData.ApiUrl;
var mph = require("../../utils/util.js");

Page({

  /**
   * 页面的初始数据
   */
  data: {// 左侧菜单列表
    res:0,
    resnum:0,
    get_adv_list:[],
    classBlen:true,
    activeIndex:-1,
    loadMoreTag:false,
    show_contlist_blen:true,
    leftClassesMenuList: [],
    adv_info:{},
    sousuoT:'',
    erjiMenuList: [],
    // 左侧菜单选中item
    selectedLeftMenuItem:0,
    // 商品列表
    productList: [{
      //   goodsId: 312,
      //   goodsImgUrl: "http://img4.imgtn.bdimg.com/it/u=2784011872,440348112&fm=26&gp=0.jpg",
      //   goodsName: "草莓蛋糕",
      //   goodsPayprice: "299.0",
      //   goodsTotalPrice: "399.0",
      //   num: 0
      }]
  },
  //index.php?act=other_member&op=get_cart
  get_cart_num() {//购物车做比较用的
    let that = this;
    let k = wx.getStorageSync('key');
    wx.request({
      url: ApiUrl + "index.php?act=other_member&op=get_cart",
      data: { act: 'other_member', op: 'get_cart', key: k },
      dataType: 'json',
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      method: 'post',
      success: function (result) {
        if (result.data.code == 200) {
          console.log('购物车做比较用的：===》', result.data.datas);
          let arrJ = [];
          for (let name in result.data.datas) {
            let arrjson = {
              key: name,
              val: result.data.datas[name]
            }
            arrJ.push(arrjson);
          }

          console.log(arrJ, that.data.productList);

          for (let i = 0; i < that.data.productList.length;i++){
            for (let j = 0; j < arrJ.length;j++){
              if (that.data.productList[i].goods_id == arrJ[j].key){
                that.data.productList[i].n = arrJ[j].val;
              }
            }
          }
          
        } else {
          //console.log(result.data.datas);
        }


        that.setData({
          productList: that.data.productList
        });
      }
    })
  },
  fenleiClick(e) {//二级分类按钮
    let that = this;
//console.log('二级分类按钮=>', e.currentTarget.dataset.ind);
    let index = e.currentTarget.dataset.ind;
    let id = e.currentTarget.dataset.gc_id;
    that.addR_chanp_list(id);
    that.setData({
      classBlen: false,
      activeIndex: index,
      show_contlist_blen:true,
    })
  },
  fenleiClick_quanbu() {
    let that = this;
    let id = wx.getStorageSync('fenlei_id');
    that.addR_chanp_list(id);
    that.setData({
      classBlen: true,
      activeIndex: -1,
    })
  },
  scrollProductList(){

  },
  addL_Nav(gc_id) {//左侧导航
    let that = this;
    wx.request({
      url: ApiUrl + "index.php?act=goods_class",
      data: {},
      dataType: 'json',
      success: function (result) {
        if (result.statusCode == 200) {
          var data = result.data.datas.class_list;
          that.data.leftClassesMenuList = data;
          // console.log(result)

          var gcid = gc_id;
          if (gcid == '') {gcid = data[0].gc_id}
          
          that.addL_Nav_child_Nav(gcid);
          that.addR_chanp_list(gcid);

          that.setData({
            leftClassesMenuList: that.data.leftClassesMenuList
          })
        }else{
//console.log(result.errMsg);
        }
      }
    })
  },
  addL_Nav_child_Nav(id){//二级导航
    let that = this;
    wx.request({
      url: ApiUrl + "index.php?act=goods_class&op=get_child_all",
      data: {
        gc_id:id
      },
      dataType: 'json',
      success: function (result) {
        // console.log('二级导航===',result);
        if (result.statusCode===200){
          if (result.data.code === 200) {
            let data = result.data.datas.class_list;
//console.log('二级导航===',data);
            that.data.erjiMenuList = data;


            //获取当前顶级分类应该显示哪个
            let parent = result.data.datas.parent;//获取当前的gc_id的所有上级id
            var list = that.data.leftClassesMenuList//获取顶级分类列表
            for (var i = 0; i < list.length; i++) {
              if (list[i].gc_id == parent[0]) {
                that.setData({
                  selectedLeftMenuItem: i
                })
              }
            }
          }
        }
        that.setData({
          erjiMenuList: that.data.erjiMenuList
        })
      }
    })
  },
  addR_chanp_list(id) {//商品列表
    wx.showLoading({
      title: "加载中..."
    })
    let that = this;
    wx.request({
      url: ApiUrl + "index.php?act=goods&op=goods_list",
      data: {
        gc_id:id
      },
      dataType: 'json',
      success: function (result) {
        if (result.statusCode == 200) {
          wx.hideLoading()
          var data = result.data.datas.goods_list;
//console.log(result);
//console.log(data);
          that.data.productList = data;

          for (let i = 0; i < that.data.productList.length;i++){
            that.data.productList[i].n = 0;
          }

          that.setData({
            productList: that.data.productList,
            // classBlen: true,
            // activeIndex: -1,
          })
          that.get_cart_num();
          if (that.data.classBlen) {
            that.addL_Nav_child_Nav(id);
            that.setData({
              classBlen: true,
              activeIndex: -1,
            })
          }
        }else{
//console.log(result.errMsg);
        }
       
      }
    })
  },
  loadMore(){//上啦刷新
    let that = this;
    that.data.loadMoreTag = true;
    that.setData({
      loadMoreTag: that.data.loadMoreTag
    })
//console.log("页面上拉页面上拉页面上拉");
    
    // that.data.productList = '{ goods_id: "101132", store_id: "2", goods_name: "雅安黄心猕猴桃 | 汁水清润 圆润饱满 果肉软糯 口感相当细腻 1颗猕猴桃=1个苹果的7倍", goods_jingle: "24粒装（70g-90g）", goods_price: "39.90" }';
    // that.setData({
    //   productList: that.data.productList
    // })
  },
  show_right_box() {
    let that = this;
    that.setData({
      show_contlist_blen: !that.data.show_contlist_blen
    })
  },
  hide_right_box() {
    let that = this;
    that.setData({
      show_contlist_blen: !that.data.show_contlist_blen
    })
  },
  addShoppingCart(k, id, num) {//购物车购买数量
    // key 当前登录令牌
    // goods_id 商品编号
    // quantity 购买数量
//console.log("当前登录令牌:" + k, "===goods_id：" + id, "======quantity："+num);
    let that = this;
    wx.request({
      url: ApiUrl + "index.php?act=member_cart&op=type_add",
      data: { key: k, goods_id: id, quantity: num },
      dataType: 'json',
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      method: 'post',
      success: function (result) {
        console.log('购买数量：' + result);
        if (result.statusCode == 200) {
          if (result.data.code == 200){
//console.log(result.data.datas);
          } else {
//console.log(result.data.datas);
          }
        } else {
//console.log(result.errMsg);
        }

      }
    })
  },
  changeGoodsNum(e) {
    let that = this;
    let id = e.currentTarget.dataset.item.goods_id;
    let key = wx.getStorageSync('key'); 
//console.log(id);
    for (let i = 0; i < that.data.productList.length;i++){
//console.log(that.data.productList[i].goods_id,id);
      if (parseInt(that.data.productList[i].goods_id) == parseInt(id)) {
        that.data.productList[i].n++;
        // that.addShoppingCart(key, id, that.data.productList[i].evaluation_count)
        that.addShoppingCart(key, id, that.data.productList[i].n)
      }
//console.log(that.data.productList[i])
    }
    that.setData({
      productList: that.data.productList
    })

    that.addshopping_num();
  },
  changeJianNum(e) {
    let that = this;
    let id = e.currentTarget.dataset.item.goods_id;
    let key = wx.getStorageSync('key'); 
//console.log(e.currentTarget.dataset.item);

    for (let i = 0; i < that.data.productList.length; i++) {
      if (that.data.productList[i].goods_id == id) {
        if (that.data.productList[i].n > -1){
          that.data.productList[i].n--;
          that.addShoppingCart(key, id, that.data.productList[i].n)
        }else{
          that.data.productList[i].n = 0;
        }
      }

    }
    that.setData({
      productList: that.data.productList
    })
    that.addshopping_num();
  },
  addshopping_num(){//购物车上左上角设置添加物品的个数！！！
    let that = this;
    that.data.res = 0;
    for (let i = 0; i < that.data.productList.length; i++) {
      if (that.data.productList[i].n > 0) {
        that.data.res += that.data.productList[i].n;
      } 
    }
    that.data.resnum++;
    let total_limit_num = wx.getStorageSync('total_limit_num');
    if (that.data.res == 0) {
      wx.setTabBarBadge({//移除tabbar右上角的文本
        index: 3,	//tabbar下标
        text: '' + ( total_limit_num)	//显示的内容
      })
    } else {
      wx.setTabBarBadge({//tabbar右上角添加文本
        index: 3, ////tabbar下标
        text: '' + (total_limit_num + that.data.resnum)	//显示的内容
      })
    };
    that.setData({
      res: that.data.res,
    })
  },
  selectClassesClick(e) {//左侧导航按钮点击切换
//console.log(e.currentTarget.dataset);
    let that = this;
    let ind = e.currentTarget.dataset.index;
    let id = e.currentTarget.dataset.id;

    that.data.selectedLeftMenuItem = ind;
//console.log('左侧导航按钮=='+that.data.selectedLeftMenuItem,id);
    that.setData({
      selectedLeftMenuItem: that.data.selectedLeftMenuItem,
      classBlen:true,
      activeIndex:-1
    })
    wx.setStorageSync('fenlei_id', id);
    if (id) {
      that.addR_chanp_list(id);
    }
  },
  showGoodsDetail(){
//console.log("产品详情页面跳转");
  },
  get_adv_list() {//分类上部分导航
    let that = this;
    console.log(111);
    wx.request({//index.php?act=other&op=get_adv_list
      url: ApiUrl + "index.php?act=other&op=get_adv_list",
      data: {
        c: '分类上部广告位'
      },
      dataType: 'json',
      method:'POST',
      success: function (result) {
        // console.log('分类上部分导航===',result);
        if (result.data.code === 200) {
          let data = result.data.datas;
          console.log('分类上部分导航===',data);
          that.data.get_adv_list = data;
        }
        that.setData({
          get_adv_list: that.data.get_adv_list
        })
      }
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let that = this;
    console.log(1111, app.globalData.gc_id)
    that.addL_Nav(app.globalData.gc_id);
    that.get_adv_list();
    that.share_tips()
    // that.addR_chanp_list('763'); 
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
  
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    let that = this;
//console.log('页面显示');
    that.get_cart_num();
    let total_limit_num = wx.getStorageSync('total_limit_num');
    that.data.res+=total_limit_num;
    if (that.data.res == 0){
      wx.removeTabBarBadge({//tabbar右上角添加文本
        index: 3, ////tabbar下标
        text: ''	//显示的内容
      })
    } else {
      wx.setTabBarBadge({//tabbar右上角添加文本
        index: 3, ////tabbar下标
        text: '' + that.data.res	//显示的内容
      })
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    let that = this;
    that.data.resnum = 0;
    console.log('页面隐藏22', that.data.resnum);
    for (let i = 0; i < that.data.productList.length; i++) {
      that.data.productList[i].n = 0;
    }
    that.data.res = 0;
    that.setData({
      productList: that.data.productList,
      res:that.data.res
    })
  
  }, 
  /** 搜索框背景文字 */
  share_tips:function() {
    var list = wx.getStorageSync('share_tips_list')
    this.setData({
      sousuoT: list
    })
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
  
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
  
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
  
  }
})